package edu.ynu.se.xiecheng.achitectureclass.project.utils;

import edu.ynu.se.xiecheng.achitectureclass.project.dao.DeviceDao;
import edu.ynu.se.xiecheng.achitectureclass.project.dao.GreenhouseDAO;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.Greenhouse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

@Component
public class GreenhouseDeviceUtils {

    @Autowired
    private GreenhouseDAO greenhouseRepository;

    @Autowired
    private DeviceDao deviceRepository;

    public Greenhouse getOrCreateGreenhouse(String boxId) {
        Optional<Greenhouse> greenhouseOptional = greenhouseRepository.findByBoxId(boxId);

        Greenhouse greenhouse;
        if (greenhouseOptional.isPresent()) {
            greenhouse = greenhouseOptional.get();
            greenhouse.setUpdateTime(new Date());
            greenhouse.setTimestamp(new Date());
            System.out.println("Greenhouse already exists: " + greenhouse.getBoxId());
        } else {
            greenhouse = new Greenhouse();
            greenhouse.setBoxId(boxId);
            greenhouse.setName(boxId+"大棚");
            greenhouse.setAddress("云南大学");
            greenhouse.setTimestamp(new Date());
            System.out.println("Creating new greenhouse: " + greenhouse.getBoxId());
        }

        greenhouseRepository.save(greenhouse);
        return greenhouse;
    }

    public Device getOrCreateDevice(String sensorId, String name, Greenhouse greenhouse) {
        Optional<Device> deviceOptional = deviceRepository.findByDeviceId(sensorId);

        Device device;
        if (deviceOptional.isPresent()) {
            device = deviceOptional.get();
            device.setUpdateTime(new Date());
            System.out.println("Device already exists: " + device.getDeviceId());
        } else {
            device = new Device();
            device.setDeviceId(sensorId);
            device.setName(name+"检测设备");
            device.setGreenhouse(greenhouse);
            System.out.println("Creating new device: " + device.getDeviceId());
        }

        deviceRepository.save(device);
        return device;
    }
}

